Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: made API token validation async! #96

Merged
merged 3 commits into from
Nov 12, 2024
Merged

Conversation

amindadgar
Copy link
Member

@amindadgar amindadgar commented Nov 12, 2024

Summary by CodeRabbit

  • New Features

    • Enhanced API key validation with asynchronous processing for improved performance.
    • Added a test case to validate behavior with an empty API key.
  • Bug Fixes

    • Improved error handling during API key validation.
  • Documentation

    • Added detailed docstrings for the API key retrieval function, clarifying parameters and return values.
  • Tests

    • Transitioned to asynchronous testing methods for better handling of async operations.
    • Updated tests to reflect the new asynchronous validation logic.

Copy link
Contributor

coderabbitai bot commented Nov 12, 2024

Walkthrough

The changes in this pull request involve significant modifications to the get_api_key function and the ValidateAPIKey class within services/api_key.py, transitioning both to asynchronous implementations. The updates include enhanced documentation for the get_api_key function and adjustments to the validation logic, which now operates asynchronously. Corresponding changes are made to the test suite in tests/integration/test_validate_token.py, where tests are adapted to use asynchronous methods, ensuring compatibility with the new validation approach. Additionally, the dependency injection for API key validation in the FastAPI routes is updated in routers/http.py.

Changes

File Change Summary
services/api_key.py - Updated get_api_key to async and added docstring.
- Changed validate method to async.
tests/integration/test_validate_token.py - Changed TestValidateToken to inherit from IsolatedAsyncioTestCase.
- Updated test methods to async and added asyncSetUp and asyncTearDown.
- Added test_validation_with_empty_api_key.
routers/http.py - Updated API key validation dependencies in /ask and /status routes to use get_api_key.

Possibly related PRs

  • Feat/93 add api key #95: The changes in this PR involve modifications to the routers/http.py file, specifically related to API key validation, which is directly connected to the updates made in the get_api_key function and ValidateAPIKey class in the main PR.

Suggested reviewers

  • cyri113

Poem

In the realm of code where bunnies play,
Async hops in a bright new way.
With keys that validate, swift and clear,
Our tests now dance, no need to fear.
So let us celebrate, with joy and cheer,
For every change brings us near! 🐇✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Outside diff range and nitpick comments (4)
services/api_key.py (1)

Line range hint 51-71: Improve the validate method implementation.

A few suggestions to enhance this method:

  1. The boolean conversion can be simplified
  2. Consider adding return type hints in the docstring

Here's a cleaner implementation:

    async def validate(self, api_key: str) -> bool:
        """
        check if the api key is available in mongodb or not

        Parameters
        ------------
        api_key : str
            the provided key to check in db

        Returns
        ---------
        valid : bool
            if the key was available in mongo collection, then return True
            else, the token is not valid and return False
+        rtype: bool
        """
        document = self.client[self.db][self.tokens_collection].find_one(
            {"token": api_key}
        )
-        return True if document else False
+        return bool(document)
tests/integration/test_validate_token.py (3)

7-13: Consider making MongoDB operations async in setup

While the transition to async testing is good, the MongoDB client initialization could be made async for consistency and to prevent potential blocking operations.

Consider updating the setup:

 async def asyncSetUp(self) -> None:
     """
     Set up test case with a test database
     """
-    self.client = MongoSingleton.get_instance().get_client()
+    self.client = await MongoSingleton.get_instance().get_async_client()
     self.validator = ValidateAPIKey()

Line range hint 46-66: Refactor duplicate test data setup

The test data insertion is duplicated across test methods. Consider extracting it to a helper method for better maintainability.

Consider adding a helper method:

async def _insert_test_tokens(self, tokens):
    """Helper method to insert test tokens
    
    Args:
        tokens (list): List of token documents to insert
    """
    try:
        await self.client[self.validator.db][self.validator.tokens_collection].insert_many(tokens)
    except Exception as e:
        print(f"Failed to insert test tokens: {e}")
        raise

Then update the test methods to use it:

await self._insert_test_tokens([
    {"id": 1, "token": "1111", "options": {}},
    {"id": 2, "token": "2222", "options": {}},
    {"id": 3, "token": "3333", "options": {}}
])

Also applies to: 77-96


102-108: Consider adding more edge cases

While testing empty API key is good, consider adding more edge cases for comprehensive validation testing.

Consider adding tests for:

  • API key with only whitespace
  • API key with special characters
  • Very long API key
  • Non-string API key types

Example:

async def test_validation_with_whitespace_api_key(self):
    """Test validation with whitespace API key"""
    valid = await self.validator.validate("   ")
    self.assertEqual(valid, False)

async def test_validation_with_special_chars(self):
    """Test validation with special characters in API key"""
    valid = await self.validator.validate("!@#$%^&*()")
    self.assertEqual(valid, False)
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 7260171 and 1515c02.

📒 Files selected for processing (2)
  • services/api_key.py (2 hunks)
  • tests/integration/test_validate_token.py (3 hunks)
🔇 Additional comments (2)
services/api_key.py (2)

13-30: LGTM! Well-documented function.

The docstring follows NumPy format and provides clear documentation of parameters, exceptions, and return values.


Line range hint 1-71: Verify async implementation in dependent modules.

The transition to async validation might require updates in modules that call these methods.

Let's check for any potential callers that need to be updated:

✅ Verification successful

Async implementation verified successfully.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for direct calls to get_api_key or ValidateAPIKey.validate
rg -l "get_api_key|ValidateAPIKey.*validate" --type py

# Search for potential FastAPI dependencies using this function
rg -l "Depends.*get_api_key" --type py

Length of output: 117

services/api_key.py Show resolved Hide resolved
tests/integration/test_validate_token.py Show resolved Hide resolved
+ wrong dependency was being applied.
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (1)
routers/http.py (1)

Issue Found: get_api_key is not defined as async in services/api_key.py.

The endpoint is updated to use get_api_key as an async dependency, which may cause runtime issues.

🔗 Analysis chain

Line range hint 20-37: LGTM: Endpoint updated to use async API key validation.

The dependency change aligns with the PR objective, and the endpoint maintains proper async/await patterns.

Let's verify the async validation is properly integrated:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the async validation implementation
# Check if the get_api_key function is properly async
ast-grep --pattern 'async def get_api_key($$$)'

# Check for any remaining sync validation calls
rg -l 'api_key_header'

Length of output: 233


Script:

#!/bin/bash
# Description: Verify if get_api_key is defined as async in services/api_key.py
ast-grep --pattern 'async def get_api_key($$)' services/api_key.py

Length of output: 68

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between aee615a and 42604d5.

📒 Files selected for processing (1)
  • routers/http.py (3 hunks)
🔇 Additional comments (2)
routers/http.py (2)

7-7: LGTM: Import added for new dependency.

The import is correctly placed and necessary for the updated dependency injection.


Line range hint 40-61: Consider making persistence operations async.

While the API key validation is now async, the persist_http operation is still synchronous and could block the endpoint. Consider updating the PersistPayload class to support async operations.

Example refactor:

- persister = PersistPayload()
- persister.persist_http(http_payload, update=True)
+ persister = PersistPayload()
+ await persister.persist_http_async(http_payload, update=True)

Let's check the persistence implementation:

#!/bin/bash
# Description: Check if PersistPayload has async support
# Look for async methods in PersistPayload
ast-grep --pattern 'class PersistPayload {
  $$$
  async def $_($$) {
    $$$
  }
  $$$
}'

@amindadgar amindadgar merged commit 4cd4702 into main Nov 12, 2024
14 checks passed
@amindadgar amindadgar linked an issue Nov 13, 2024 that may be closed by this pull request
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Add API key support for http server
1 participant